package com.umxwe.kill.common;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionTwo extends Thread {

    private Lock lock;

    private int count;

    private String str;
    private int flag;
    Condition A;
    Condition B;

    public ConditionTwo(String str, int flag, int count, Lock lock, Condition A, Condition B) {
        this.str = str;
        this.flag = flag;
        this.A = A;
        this.B = B;
        this.count = count;
        this.lock = lock;
    }

    @Override
    public void run() {
        try {
            lock.lock();
            while (count<5) {
                System.out.println(" str = " + str+" count =" +count);
                count++;
                // 唤醒 B 线程
                B.signal();
                // 暂停自己进程
                A.await();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            B.signal();
            lock.unlock();
        }
    }


    public static void main(String[] args) throws InterruptedException {

        Lock lock = new ReentrantLock();

        int count = 0;

        Condition A = lock.newCondition();
        Condition B = lock.newCondition();
        Condition C = lock.newCondition();

        new ConditionTwo("a", 0,count,lock, A, B).start();

        // 必须要加 这个限制，不然可能不是a 先执行

        Thread.sleep(500);

        new ConditionTwo("b", 1,count,lock,  B, C).start();
        new ConditionTwo("c", 2,count,lock,  C, A).start();

    }
}